<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="ctxPath" value="${pageContext.request.contextPath}"/>

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <title>部门列表</title>
    <link rel = "Shortcut Icon" href="${ctxPath}/static/images/user_list.ico"/>
    <link rel="stylesheet" href="${ctxPath}/static/layui/css/layui.css?t=1554901098009" media="all">
    <style>
        body{margin: 10px;}
        .demo-carousel{height: 200px; line-height: 200px; text-align: center;}
    </style>

    <style>
        #tbl{ margin-top:15px; margin-left:25px; }
        #tbl th{ height:45px; }
        #tbl td{
            font-weight:normal; height:45px;
            font-family:微软雅黑; font-size:17px;
        }
        #tbl [type='text']{
            height:28px; font-size:17px;
            text-indent:0.3em;
        }
        #tbl select { width:200px; height:32px; font-size:17px; }
        #tbl td:nth-child(1){ width:80px; }
        #tbl td:nth-child(2){ width:350px; }
        input[readonly]{
            background:#DDD;
            color:#333; border:1px solid #666;
        }
        div.layui-layer-title{
            background:#666; color:#EEE;
            font-size:15px;
        }

        label.layui-form-label{
            width:60px;
            padding-left:5px;
            padding-right:10px;
        }
        .layui-form-item .layui-inline {
            margin-right:0px;
        }
    </style>
</head>
<body>

<form class="layui-form">
    <div class="layui-form-item" style="margin-bottom:5px;">
        <div class="layui-inline">
            <label class="layui-form-label">部门名称</label>
            <div class="layui-input-inline">
                <input type="text" name="frmDeptName" id="frmDeptName"
                       autocomplete="off" class="layui-input">
            </div>
        </div>

        <div class="layui-inline">
            <label class="layui-form-label">部门ID</label>
            <div class="layui-input-inline">
                <input type="text" name="frmDeptId" id="frmDeptId"
                       autocomplete="off" class="layui-input">
            </div>
        </div>

        <div class="layui-inline">
            <label class="layui-form-label">部门描述</label>
            <div class="layui-input-inline">
                <input type="text" name="frmDeptDesc"
                       id="frmDeptDesc" autocomplete="off"
                       class="layui-input">
            </div>
        </div>
    </div>

    <div class="layui-form-item">

        <label class="layui-form-label">部门等级</label>
        <div class="layui-input-inline">
            <select name="frmDeptLevel" id="frmDeptLevel">
                <option value="">请选择等级</option>
                <option value="lv1">lv1</option>
                <option value="lv2">lv2</option>
                <option value="lv3">lv3</option>
                <option value="lv4">lv4</option>
            </select>
        </div>

        <button type="button"
                class="layui-btn" onclick="testSearch();"
                style="margin-left:30px;">立即搜索</button>
        <button type="reset"
                class="layui-btn layui-btn-normal"
                onclick="reloadPage('return')"
                style="margin-left:10px;">重置</button>
    </div>
    </div>
</form>


<script>
    function updateSelect( id ){
        var $sel = $( id );
        var $dd = $sel.parent().find("dd");
        for(var idx=0; idx<$dd.size(); idx++){
            var obj = $dd[ idx ];
            if( $(obj).hasClass('layui-this') ){
                var op = $( id +" option")[idx];
                $(op).attr("selected",true);
            }
        }
    }
    //表单的数据项
    var schFlds = [
        {key:'deptName',id:'#frmDeptName'},
        {key:'id',id:'#frmDeptId'},
        {key:'deptDesc',id:'#frmDeptDesc'},
        {key:'level',id:'#frmDeptLevel'},
    ];

    function testSearch(){
        //----- [填入代码] -----
        updateSelect("#frmDeptLevel");
        var cond = {};
        //迭代搜素的字段
        for (var i = 0; i < schFlds.length; i++) {
            var key = schFlds[i].key;
            var itemId = schFlds[i].id;
            //使用键值法来设置对象的key，value
            var val = $(itemId).val();
            if (val!= null) {
                cond[key] = val;
            }
        }
        console.log("搜索条件");
        console.log(cond);
        layui.table.reload(
            //表格ID
            'deptTbl',
            {
                //数据接口
                url:'${ctxPath}/Dept/jsonList',
                //搜索条件
                where:cond,
                page: {
                    //默认第一页
                    curr:1,
                }
            }
        );
    }
</script>


<table class="layui-hide" id="demo" lay-filter="test">
</table>

<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<script src="${ctxPath}/static/layui/layui.js?t=1554901098009" charset="utf-8">
</script>
<script src="${ctxPath}/static/js/jquery-1.11.1.min.js"></script>
<script src="${ctxPath}/static/js/form.js"></script>


<script>
    layui.config({
        version: '1554901098009' //为了更新 js 缓存，可忽略
    });

    layui.use(
        ['laydate', 'laypage', 'layer', 'table', 'carousel', 'upload', 'element', 'slider'],
        function(){
            var laydate = layui.laydate //日期
                ,laypage = layui.laypage //分页
                ,layer = layui.layer //弹层
                ,table = layui.table //表格
                ,carousel = layui.carousel //轮播
                ,upload = layui.upload //上传
                ,element = layui.element //元素操作
                ,slider = layui.slider //滑块

            //{ps} ?op=update  ?op=add
            var op = "${param['op']}";
            if( op=='add' ){
                layer.msg('添加部门成功..');
            }else if(op=='update'){
                layer.msg('更新部门成功..');
            }else {
                layer.msg('正在加载数据..');
            }

            //{ps} 监听Tab切换
            element.on('tab(demo)', function(data){
                layer.tips('切换了 '+ data.index +': '+ this.innerHTML, this, {
                    tips: 1
                });
            });

            //{ps} 执行一个 table 实例
            var ran = Math.random();
            table.render({
                elem: '#demo'
                ,height: 750
                ,url: '${ctxPath}/Dept/jsonList?ran='+ ran   //数据接口
                ,title: '部门列表'
                ,page: true     //{ps} 开启分页
                ,id: 'deptTbl'
                //{ps} 开启工具栏，此处显示默认图标，可以自定义模板，详见文档
                //toolbar: 'default'
                ,totalRow: false   //{ps} 开启合计行
                ,cols: [[          //{ps} 表头
                    {type: 'checkbox', fixed: 'left'},
                    {field: 'id', title: '部门ID', width:130, sort: true, fixed: 'left'},
                    {field: 'parentId', title: '上级ID', width:130},
                    {field: 'parentName', title: '隶属部门', width:150},
                    {field: 'deptName',title: '部门名称', width:155},
                    {field: 'deptDesc',title: '部门描述', width:240},
                    {field: 'level',title: '部门级别', width:120},
                    {fixed: 'right', width: 180, align:'center', toolbar: '#barDemo'}
                ]]
            });

            //{ps} 监听头工具栏事件
            table.on('toolbar(test)', function(obj){
                var checkStatus = table.checkStatus(obj.config.id)
                    ,data = checkStatus.data; //获取选中的数据
                switch(obj.event){
                    case 'add':
                        layer.msg('添加');
                        break;
                    case 'update':
                        if(data.length === 0){
                            layer.msg('请选择一行');
                        } else if(data.length > 1){
                            layer.msg('只能同时编辑一个');
                        } else {
                            layer.alert('编辑 [id]: '+ checkStatus.data[0].id);
                        }
                        break;
                    case 'delete':
                        if(data.length === 0){
                            layer.msg('请选择一行');
                        } else {
                            layer.msg('删除[id]: '+ checkStatus.data[0].id);
                        }
                        break;
                };
            });

            //{ps} 监听行工具事件
            //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            table.on('tool(test)', function(obj){
                var data = obj.data     //获得当前行数据
                    , layEvent = obj.event; //获得 lay-event 对应的值

                if(layEvent === 'detail'){
                    layer.msg('查看操作');
                } else if(layEvent === 'del'){
                    layer.confirm('是否要删除部门？', function(index){
                        layer.msg("正在删除部门....");
                        delDept(data['id'])
                    });
                } else if(layEvent === 'edit'){
                    layer.msg('编辑部门...');
                    editUser( data['id'] );
                }
            });

            //执行一个轮播实例
            carousel.render({
                elem: '#test1'
                ,width: '100%' //设置容器宽度
                ,height: 200
                ,arrow: 'none' //不显示箭头
                ,anim: 'fade' //切换动画方式
            });



            //分页
            laypage.render({
                elem: 'deptTbl' //分页容器的id
                ,count: 8        //总页数
                ,skin: '#1E9FFF' //自定义选中色值
                ,limit: 3
                //,skip: true    //开启跳页
                ,jump: function(obj, first){
                    if(!first){
                        layer.msg('第'+ obj.curr +'页', {offset: 'b'});
                    }
                }
            });

            slider.render({
                elem: '#sliderDemo'
                ,input: true //输入框
            });

        });
</script>

<!-- {ps} 编写我们的 js 代码! -->
<script>
    //{选项数据}

    var level_data = [
        {text:"请选择部门等级",val:""},
        {text:"lv1",val:"lv1"},
        {text:"lv2",val:"lv2"},
        {text:"lv3",val:"lv3"},
        {text:"lv4",val:"lv4"},
    ];
    var parentDeptId_data = [
        {text:"请选择上级ID",val:""},
        {text:"d01",val:"d01"},
        {text:"d02",val:"d02"},
        {text:"d03",val:"d03"},
        {text:"d04",val:"d04"},
        {text:"d05",val:"d05"},
        {text:"d06",val:"d06"},
        {text:"d07",val:"d07"},
        {text:"d08",val:"d08"},
        {text:"d09",val:"d09"},
        {text:"d10",val:"d10"},
        {text:"sys",val:"sys"},
    ];

    function editUser( deptId ){
        $.ajax(
            {
                url:'${ctxPath}/Dept/getDept',
                type:'post',
                data:{id:deptId},
                dataType:'json',
                success:function(respTxt){
                    var ret = respTxt['result'];
                    if(ret=='success'){
                        //{1}获取 dept 对象
                        var dept = respTxt['dept'];
                        //{2}生成表格
                        var tbl = makeTable( gInputs, dept );
                        //{3}弹出对话框
                        showBox( tbl );
                    }else{
                        //{4}弹出错误提示。
                        layer.msg( respTxt.cause );
                    }
                }
            }
        );
    }

    //{ps}用来生成表单
    //title:标题, name:表单项目名, readonly:只读, type:文本,下拉菜单,隐藏域
    var gInputs = [
        {title:"部门ID", name:"id", readonly:"readonly", type:"text"},
        {title:"上级ID", name:"parentId", type:"select",options:parentDeptId_data},
        {title:"隶属部门", name:"parentName", type:"text"},
        {title:"部门名称", name:"deptName", type:"text"},
        {title:"部门描述", name:"deptDesc", type:"text"},
        {title:"部门级别", name:"level", type:"select",options:level_data},
        {name:"id", type:"hide"}
    ];


    function showBox( tbl ){
        layer.open({
            type: 1
            ,title: '编辑部门'
            ,closeBtn: false
            ,area: ['450px','395px']
            ,shade: 0
            ,id: 'LAY_layuipro'   //设定一个 id, 防止重复弹出
            ,btn: ['保存编辑', '关闭对话框']
            ,btnAlign: 'c'
            ,moveType: 1          //拖拽模式, 0 或者 1
            ,content: tbl
            ,yes: function(){
                updateDept();
            }
            ,success: function( layero ){
            }
        });
    }

    var items = [
        "id", "parentId", "deptName",
        "deptDesc", "level"
    ];

    //{ps} 抓取表单数据
    function pickData(){
        //定义一个对象, 存放所有数据。
        var obj = {};
        for( var i=0; i<items.length; i++ ){
            var id = items[i];  //获取表单项 id
            var val = $("#"+id).val();
            //{3}填入 obj 对象
            obj[ id ] = val;
        }
        return obj;
    }

    /*
     *  函数: updateDept
     *  提交数据, 通过 ajax 对象。
     *	提交地址: /User/saveDept
     */
    function updateDept(){
        var obj = pickData();  //抓取表单数据..
        console.log( obj );
        $.ajax(
            {
                url:'${ctxPath}/Dept/update',
                type:'post',
                data:obj,
                dataType:'json',
                success:function( respTxt ){
                    console.log( respTxt );
                    var ret = respTxt['result'];
                    if( ret=='success' ){
                        layer.msg('修改部门成功');
                        setTimeout(
                            function(){
                                reloadPage('edit');
                            }, 2500 );
                    }else{
                        layer.msg( respTxt.cause );
                    }
                }
            }
        );
    }

    function reloadPage( op ){
        window.location = '${ctxPath}/Dept/viewList?op='+ op;
    }

    function delDept( _id ){
        var obj = pickData();  //抓取表单数据..

        $.ajax(
            {
                url:'${ctxPath}/Dept/delete',
                type:'post',
                data: {id:_id},
                dataType:'json',
                success:function( respTxt ){
                    console.log( respTxt );
                    var ret = respTxt['result'];
                    if( ret=='success' ){
                        layer.msg('删除部门成功:'+ _id);
                        setTimeout(
                            function(){
                                reloadPage('edit');
                            }, 2500 );
                    }else{
                        layer.msg( respTxt.cause );
                    }
                }
            }
        );
    }
</script>



</body>
</html>
